/* eslint-disable react/jsx-indent */
/* eslint-disable no-nested-ternary */
import React, { Component, Suspense } from "react";
import PageHeaderWrapper from "@/components/PageHeaderWrapper";
import { exportQAHistories } from "@/services/download";
import qs from "qs";
import { connect } from "dva";
import PageLoading from "@/components/PageLoading";
import { FormattedMessage, formatMessage } from "umi-plugin-react/locale";
import { routerRedux } from "dva/router";
import {
	Card, Row, Col, Form, Input, Button, message, Icon, Checkbox, Pagination,
	Table, Tag, Select, Modal, Radio, Spin, Upload, Tabs, Drawer, Tooltip,
} from "antd";
import Custom from "./custom.js";
// import Service from '@/modules/service/index'
import Service from "../../../modules/service";
import deleteimg from "@/assets/buttonimg/delete.png";
import useimg from "@/assets/buttonimg/use.png";
const { TabPane } = Tabs;
const FormItem = Form.Item;
const Search = Input.Search;
const InputGroup = Input.Group;
import styles from "./index.less";
const { Option } = Select;
const { TextArea } = Input;
const RadioGroup = Radio.Group;
import pen from "../../../assets/icons/bi.png";
import ljx from "../../../assets/icons/垃圾箱.png";
import UserSession from "@/UserSession";
import tableDataCheck from "@/utils/isBackPrevPage";

class CustomNew extends Component {
	state = {
		dictType: "",
		page: 1,
		limit: 10,
		dictNames: "",
		listA: [],
		totalA: "",
		login: true,
		showModel1: false,
		showModel2: false,
		formatC: "",
		showUse: false,
	};

	componentDidMount() {
		const params = window.location.href.split("?");
		if (params[1]) {
			this.setState({ page: params[1].split("=")[0] === "page" && params[1].split("=")[1] ? parseInt(params[1].split("=")[1]) : 1, }, () => {
				this.fetch();
			});
		} else {
			this.fetch();
		}
	}

	// 主页列表
	fetch = () => {
		this.setState({ login: true });
		const { dispatch, currentUser, tabKey, urlPrefix } = this.props;
		const { dictType, page, limit, dictNames } = this.state;

		this.reqRef = requestAnimationFrame(() => {
			dispatch({
				type: "customDictionary/fetch",
				payload: {
					current: page,
					size: limit,
					search: dictNames,
					urlPrefix,
				},
				callback: (res) => {
					// res.list.map((item, index) => {
					//   item['key'] = index
					// })
					this.props.totalAHome(res.total);
					this.setState({
						listA: res.records,
						totalA: Number(res.total),
						login: false,
					});
				},
			});
		});
	};

	// 主页增加
	coreWordOne = () => {
		let userInfo = this.props.form.getFieldsValue(); // 获取数据
		this.props.form.validateFields((err, values) => {
			// 校验方法
			let userInfo = this.props.form.getFieldsValue(); // 获取数据
			if (!err) {
				let obj;
				if (userInfo.dictionaryTypes === "1") {
					obj = true;
				};
				if (userInfo.dictionaryTypes === "2") {
					obj = false;
				};
				const { dispatch, currentUser } = this.props;
				this.reqRef = requestAnimationFrame(() => {
					dispatch({
						type: "customDictionary/fetchc",
						payload: { name: userInfo.corewordone, isEnum: obj },
						callback: (res) => {
							if (typeof res.code !== 'undefined' && res.code !== 0) {
								// message["error"](`${res.message}`);
							} else {
								message["info"](`${res.message}`);
								this.setState({ showModel1: false, formatC: "" }, () => {
									this.props.form.setFields({ corewordone: "" });
									this.fetch();
								});
							}
						},
					});
				});
			}
		});
	};

	// 子页面修改内容
	enumeration = () => {
		this.props.form.setFields({ coreword: "" });
		this.props.form.setFields({ synonym: "" });
		this.setState({
			formatA: "",
			formatB: "",
			showModel2: true,
			itemId: "",
		});
	};

	// 主页添加内容
	addContent = () => {
		this.setState({
			showModel1: true,
		});
	};

	handleDeleteAxios = (item) => {
		const { dispatch, currentUser } = this.props;
		this.reqRef = requestAnimationFrame(() => {
			dispatch({
				type: "customDictionary/fetchd",
				payload: { id: item.id },
				callback: (res) => {
					message.success(`${res.message}`);
					const { listA, page } = this.state;
					const newCurrent = tableDataCheck(listA, page, [item.id]);
					this.setState({ page: newCurrent }, () => {
						this.fetch();
					});
				},
			});
		});
	};

	// 主页删除
	handleDeletes = (item) => {
		if (item.isUsing) {
			Modal["confirm"]({
				title: <FormattedMessage 
					id="app.customDictionary.customNew.delete.title" 
					values={{ name: item.name }}
				/>,
				content: <FormattedMessage 
					id="app.customDictionary.customNew.delete.confirm" 
				/>,
				okText: <FormattedMessage 
					id="app.customDictionary.customNew.delete" 
				/>,
				cancelText: <FormattedMessage 
					id="app.customDictionary.customNew.cancel" 
				/>,
				onOk: () => {
					this.handleDeleteAxios(item);
				},
				onCancel() { },
			});
		} else {
			Modal["confirm"]({
				title: <FormattedMessage 
					id="app.customDictionary.customNew.delete.entity.confirm" 
				/>,
				okText: <FormattedMessage 
					id="app.customDictionary.customNew.delete" 
				/>,
				cancelText: <FormattedMessage 
					id="app.customDictionary.customNew.cancel" 
				/>,
				onOk: () => {
					this.handleDeleteAxios(item);
				},
				onCancel() { },
			});
		}
	};

	handleEdit = (item) => {
		const { dispatch, tabKey, urlPrefix } = this.props;

		const { page } = this.state;
		if (item.isEnum) {
			// 可枚举
			console.log(item);
			dispatch(
				routerRedux.push({
					pathname: `/knowledgeDesign/customDictionary/enumerable/${item.id}/${urlPrefix ? urlPrefix : ""
						}`,
					query: { name: item.name, page },
				})
			);
		}
		if (!item.isEnum) {
			// 不可枚举
			dispatch(
				routerRedux.push({
					pathname: `/knowledgeDesign/customDictionary/noEnumerationNew/${item.id}/${urlPrefix ? urlPrefix : ""
						}`,
					query: { id: item.id, name: item.name, page },
				})
			);
		}
	};

	inSue = (item) => {
		// basicDictSlotList
		// const { dispatch, currentUser } = this.props;
		// this.reqRef = requestAnimationFrame(() => {
		//   dispatch({
		//     type: 'customDictionary/basicDictSlotList',
		//     payload: { id:item.id,page:1,limit:99999 },
		//     callback: res => {
		//
		//     },
		//   });
		// });

		this.setState({ item: item }, () => {
			this.openClose();
		});
	};

	openClose = () => {
		this.setState({ showUse: true });
	};

	onClose = () => {
		this.setState({
			showUse: false,
		});
	};

	callback = (key) => { };

	onChangeA = (val) => {
		// 页数选择

		this.setState({ page: val, }, () => {
			this.fetch();
		});
	};

	// 每页显示多少条数据
	onShowSizeChangeA = (current, pageSize) => {
		this.setState(
			{
				page: current,
				limit: pageSize,
			},
			() => {
				this.fetch();
			}
		);
	};

	Tooltipzdy = () => {
		return (
			<div>
				<FormattedMessage 
					id="app.customDictionary.customNew.addEntity" 
				/>
				<span style={{ marginLeft: 12, paddingTop: 3 }}>
					<Tooltip
						placement='top'
						title={<FormattedMessage 
							id="app.customDictionary.customNew.entity.tooltip" 
						/>}
						arrowPointAtCenter>
						<Icon style={{ fontSize: 14 }} type='info-circle' />
					</Tooltip>
				</span>
			</div>
		);
	};

	checkField(rule, value, callback) {
		const reg = /^[\u4e00-\u9fa5a-zA-Z0-9]+$/g;
		if (rule.field === "corewordone") {
			if (value) {
				if (reg.test(value)) {
					if (value.length > 20 || value.length < 0) {
						callback("支持20位以内大小写字母、数字和中文");
					} else {
						callback();
					}
				} else {
					callback("支持20位以内大小写字母、数字和中文");
				}
			} else {
				callback("支持20位以内大小写字母、数字和中文");
			}
		}
	}

	// eslint-disable-next-line react/sort-comp
	render() {
		const { getFieldDecorator } = this.props.form;
		const { tabKey } = this.props;

		let urlPrefix = "";

		if (tabKey == 2) {
			urlPrefix = "headquarters";
		}


		const FormItemLayont = {
			labelCol: {
				// 文字
				xs: 24,
				sm: 4,
			},
			wrapperCol: {
				// 输入框
				xs: 24,
				sm: 20,
			},
		};
		const columns = [
			{
				title: <FormattedMessage 
					id="app.customDictionary.customNew.entity.name" 
				/>,
				width: "calc(30vw)",
				dataIndex: "name", //返回的索引值
			},
			{
				title: <FormattedMessage 
					id="app.customDictionary.customNew.entity.type" 
				/>,
				width: "calc(30vw)",
				dataIndex: "isEnum",
				render(sex) {
					return sex === true ? 
						formatMessage({ 
							id: 'app.customDictionary.customNew.enumerable.type', 
						}) : 
						formatMessage({ 
							id: 'app.customDictionary.customNew.nonenumerable.type', 
						});
				},
			},
			{
				title: <FormattedMessage 
					id="app.customDictionary.customNew.actions" 
				/>,
				dataIndex: "sex",
				render: (text, item) => {
					return (
						<div className={styles.pb}>
							<div className={styles.buttongl} onClick={text => this.handleEdit(item)}>
								<img style={{ marginRight: 5 }} src={pen} />
								<span style={{ marginBottom: 1 }}>
									{urlPrefix && tabKey == 2 ? 
										<FormattedMessage 
											id="app.customDictionary.customNew.view" 
										/> : 
										<FormattedMessage 
											id="app.customDictionary.customNew.edit" 
										/>
									}
								</span>
							</div>
							{urlPrefix && tabKey == 2 ? null : (
								<div style={{ marginLeft: 10, background: "#e8313b" }} className={styles.buttongl} onClick={text => this.handleDeletes(item)}>
									<img src={deleteimg} style={{ marginRight: 5 }} />
									<span style={{ marginBottom: 1 }}>
										<FormattedMessage id='app.customDictionary.customNew.delete' />
									</span>
								</div>
							)}
							{item.isUsing === true ? (
								<div className={styles.buttongl} onClick={text => this.inSue(item)} style={{ marginLeft: 10, background: "#09B2FF" }}>
									<img src={staticPath + "/useing.svg"} style={{ marginRight: 5 }} />
									<span style={{ marginBottom: 1 }}>
										<FormattedMessage 
											id="app.customDictionary.customNew.inUse" 
										/>
									</span>
								</div>
							) : null}
						</div>
					);
				},
			},
		];

		return (
			<div>
				<div style={{ display: 'flex', justifyContent: 'space-between' }}>
					<span className={styles.right} style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
													<Input
													placeholder={formatMessage({ 
														id: "app.customDictionary.customNew.search.placeholder"
													})}
													onChange={e => this.setState({ dictNames: e.target.value })}
													style={{ width: 323 }}
												/>
												<Button type='primary' onClick={() => this.setState({ page: 1 }, () => this.fetch())}>
													{formatMessage({ 
														id: "app.customDictionary.customNew.search", 
													})}
												</Button>
					</span>
					<span>
						{urlPrefix ? null : (
							<span className='zdyButtonA' style={{ width: 90 }}>
								<Button type='primary' onClick={this.addContent} icon='plus'>
									{formatMessage({ 
										id: "app.customDictionary.customNew.add", 
									})}
								</Button>
							</span>
						)}
					</span>
				</div>
				<Spin spinning={this.state.login}>
					<Table
						className='zdyTable'
						style={{ padding: "20px 0px 0px 0px" }}
						columns={columns}
						// key='id'
						rowKey={"id"}
						dataSource={this.state.listA} //数据
						pagination={false}
					/>
					{this.state.totalA > 10 ? (
						<Pagination
							style={{ textAlign: 'right', marginTop: 16 }}
							total={this.state.totalA}
							pageSize={this.state.limit}
							current={this.state.page}
							showSizeChanger={true}
							// showQuickJumper={true}
							onChange={this.onChangeA}
							// onShowSizeChange={this.onShowSizeChangeA}
						/>
					) : null}
				</Spin>
				<Modal
					className='modelZdy'
					title={this.Tooltipzdy()}
					visible={this.state.showModel1}
					okText={<FormattedMessage id='app.customDictionary.save' />}
					cancelText={<FormattedMessage id='app.customDictionary.cancel' />}
					onCancel={() => {
						this.props.form.setFields({ corewordone: "" });
						this.setState({ showModel1: false });
					}}
					onOk={this.coreWordOne} // 确定方法开出去
				>
					<Form layout='horizontal'>
						<FormItem
																label={<FormattedMessage 
																	id="app.customDictionary.customNew.entityName.label" 
																/>}
							onSubmit={this.coreWordOne}
							{...FormItemLayont}>
							{getFieldDecorator("corewordone", {
								initialValue: `${this.state.formatC}`,
								rules: [
									{ required: true, message: <FormattedMessage 
										id="app.customDictionary.customNew.entityName.required" 
									/> },
									{ validator: this.checkField },
								],
							})(<Input />)}
						</FormItem>
						<FormItem 
							label={formatMessage({ 
								id: 'app.customDictionary.customNew.entityType.label',
							})} 
							{...FormItemLayont}>
							{getFieldDecorator("dictionaryTypes", { initialValue: "1" })(
								<RadioGroup>
									<div className={styles.newline}>
										<Radio value='1'>
											<FormattedMessage id='app.customDictionary.enumerable-type' />
										</Radio>
										<span style={{ color: "#cccccc" }}>
											<FormattedMessage id='app.customDictionary.enumerable-typetext' />
										</span>
										<Radio value='2'>
											<FormattedMessage id='app.customDictionary.noenumerable-type' />
										</Radio>
										<span style={{ color: "#cccccc" }}>
											<FormattedMessage id='app.customDictionary.noenumerable-typetext' />
										</span>
									</div>
								</RadioGroup>
							)}
						</FormItem>
					</Form>
				</Modal>
				<Drawer 
					title={<FormattedMessage 
						id="app.customDictionary.customNew.usageStatus" 
					/>} 
					placement='right' 
					closable 
					onClose={this.onClose} 
					visible={this.state.showUse} 
					width={800} 
					destroyOnClose
				>
					<Service item={this.state.item} type={"custom"} urlPrefix={urlPrefix} />
				</Drawer>
			</div>
		);
	}
}

export default connect(({ user }) => ({
	// 全局数据
	currentUser: user.currentUser,
}))(Form.create()(CustomNew));